<template>
  <div class="play-bar" :class="{ show: !toggle }">
    <div class="fold" :class="{ turn: toggle }">
      <yin-icon :icon="iconList.ZHEDIE" @click="toggle = !toggle"></yin-icon>
    </div>
    <!--播放进度-->
    <el-slider
      class="progress"
      v-model="nowTime"
      @change="changeTime"
      :min="0"
      :max="100"
      size="small"
    ></el-slider>
    <div class="control-box">
      <div class="info-box">
        <el-image
          class="song-bar-img"
          fit="contain"
          :src="attachImageUrl(songPic)"
          @click="goPlayerPage"
        />
        <div v-if="songIdVO">
          <div class="song-info">
            {{ songTitle }} - {{ singerName }}
          </div>
          <div class="time-info">{{ startTime }} / {{ endTime }}</div>
        </div>
      </div>
      <div class="song-ctr">
        <yin-icon
          class="yin-play-show"
          :icon="playStateList[playStateIndex]"
          @click="changePlayState"
        ></yin-icon>
        <!--上一首-->
        <yin-icon
          class="yin-play-show"
          :icon="iconList.SHANGYISHOU"
          @click="prev"
        ></yin-icon>
        <!--播放-->
        <yin-icon :icon="playBtnIcon" @click="togglePlay" />
        <!--下一首-->
        <yin-icon
          class="yin-play-show"
          :icon="iconList.XIAYISHOU"
          @click="next"
        ></yin-icon>
        <!--音量-->
        <el-dropdown class="yin-play-show" trigger="click">
          <yin-icon v-if="volume !== 0" :icon="iconList.YINLIANG"></yin-icon>
          <yin-icon v-else :icon="iconList.JINGYIN"></yin-icon>
          <template #dropdown>
            <el-dropdown-menu>
              <el-slider
                class="yin-slider"
                style="height: 150px; margin: 10px 0"
                v-model="storeVolume"
                :vertical="true"
              ></el-slider>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="song-ctr song-edit">
        <!--收藏-->
        <yin-icon
          class="yin-play-show"
          :class="{ active: isCollection }"
          :icon="isCollection ? iconList.like : iconList.dislike"
          @click="changeCollection"
        ></yin-icon>
        <!--下载-->
        <yin-icon
          class="yin-play-show"
          :icon="iconList.download"
          @click="downloadMusic({
            songUrl,
            songName: `${singerName}-${songTitle}`,
          })"
        />
        <!--歌曲列表-->
        <yin-icon :icon="iconList.LIEBIAO" @click="changeAside"></yin-icon>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {
  ref,
  watch,
  onMounted,
  getCurrentInstance,
} from 'vue';
import type { ComponentInternalInstance } from 'vue';
import { storeToRefs } from 'pinia';
import mixin from '@/mixins/mixin';
import YinIcon from './YinIcon.vue';
import { HttpManager, attachImageUrl } from '@/api';
import { formatSeconds } from '@/utils';
import { Icon, RouterName } from '@/enums';
import { useSongStore, useUserStore, useConfigureStore } from '@/store';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { routerManager, playMusic, checkStatus, downloadMusic } = mixin();
const attachImageUrl = HttpManager.attachImageUrl;

// Store实例
const songStore = useSongStore();
const userStore = useUserStore();
const configStore = useConfigureStore();

// 使用storeToRefs保持响应式
const {
  isPlay,
  playBtnIcon,
  songId: songIdVO,
  songUrl,
  songTitle,
  singerName,
  songPic,
  curTime,
  duration,
  currentPlayList,
  currentPlayIndex,
  autoNext,
  volume: storeVolume
} = storeToRefs(songStore);

const { userId: userIdVO } = storeToRefs(userStore);
const { token, showAside } = storeToRefs(configStore);

// 本地响应式状态
const isCollection = ref(false);
const startTime = ref('00:00');
const endTime = ref('00:00');
const nowTime = ref(0);
const toggle = ref(true);
const localVolume = ref(50);
const playState = ref<Icon>(Icon.XUNHUAN);
const playStateIndex = ref(0);
const playStateList = ref<Icon[]>([Icon.XUNHUAN, Icon.LUANXU]);

// 图标列表
const iconList: Record<string, Icon> = {
  download: Icon.XIAZAI,
  ZHEDIE: Icon.ZHEDIE,
  SHANGYISHOU: Icon.SHANGYISHOU,
  XIAYISHOU: Icon.XIAYISHOU,
  YINLIANG: Icon.YINLIANG1,
  JINGYIN: Icon.JINGYIN,
  LIEBIAO: Icon.LIEBIAO,
  dislike: Icon.Dislike,
  like: Icon.Like,
};

// 音量同步处理
watch(localVolume, (newVal) => {
  storeVolume.value = newVal / 100;
});

// 状态监听
watch(songIdVO, initCollection);
watch(token, (value) => {
  !value && (isCollection.value = false)
})
watch(curTime, () => {
  startTime.value = formatSeconds(curTime.value);
  endTime.value = formatSeconds(duration.value);
  nowTime.value = (curTime.value / duration.value) * 100;
});
watch(isPlay, (value) => {
  songStore.playBtnIcon = value ? Icon.ZANTING : Icon.BOFANG;
});
watch(autoNext, next);

// 生命周期
onMounted(() => songIdVO.value && initCollection());

// 方法
async function initCollection() {
  if (!checkStatus(false)) return;

  try {
    const result = await HttpManager.isCollection(userStore.userId,0,songIdVO.value);
    isCollection.value = result.data;
  } catch (error) {
    console.error('收藏状态获取失败:', error);
  }
}

async function changeCollection() {
  if (!checkStatus()) return;

  try {
    const params = { userId: userIdVO.value, type: "0", songId: songIdVO.value };
    const result = isCollection.value
      ? await HttpManager.deleteCollection(userIdVO.value, songIdVO.value)
      : await HttpManager.setCollection(params);
    // 更新收藏状态
    initCollection()

    proxy.$message({ message: result.message, type: result.type });
    isCollection.value = result.data;
  } catch (error) {
    console.error('收藏操作失败:', error);
  }
}

function changeAside() {
  configStore.showAside = !configStore.showAside;
}

function togglePlay() {
  songStore.isPlay = !songStore.isPlay;
}

function changeTime(newVal: number) {
  nowTime.value = newVal;
  songStore.changeTime = duration.value * (nowTime.value * 0.01);
}

function changePlayState() {
  playStateIndex.value = playStateIndex.value >= playStateList.value.length - 1 ? 0 : playStateIndex.value + 1;
  playState.value = playStateList.value[playStateIndex.value];
}

function handleTrackNavigation(
  getNewIndex: (index: number, length: number) => number
) {
  if (playState.value === Icon.LUANXU) {
    handleRandomPlay();
  } else if (currentPlayIndex.value !== -1 && currentPlayList.value.length > 1) {
    const newIndex = getNewIndex(currentPlayIndex.value, currentPlayList.value.length);
    songStore.currentPlayIndex = newIndex;
    toPlay(currentPlayList.value[newIndex].url);
  }
}

function handleRandomPlay() {
  let playIndex = Math.floor(Math.random() * currentPlayList.value.length);
  playIndex = playIndex === currentPlayIndex.value ? playIndex + 1 : playIndex;
  songStore.currentPlayIndex = playIndex;
  toPlay(currentPlayList.value[playIndex].url);
}

function prev() {
  handleTrackNavigation((index, length) => index > 0 ? index - 1 : length - 1);
}

function next() {
  handleTrackNavigation((index, length) => index < length - 1 ? index + 1 : 0);
}

function toPlay(url: string) {
  if (url && url !== songUrl.value && currentPlayList.value.length) {
    const song = currentPlayList.value[currentPlayIndex.value];
    playMusic({
      id: song.id,
      url,
      pic: song.pic,
      index: currentPlayIndex.value,
      name: song.name,
      lyric: song.lyric,
      currentSongList: currentPlayList.value,
    });
  }
}

function goPlayerPage() {
  routerManager(RouterName.Lyric, {
    path: `${RouterName.Lyric}/${songIdVO.value}`
  });
}
</script>

<style lang="scss" scoped>
@import "@/assets/css/yin-play-bar.scss";
</style>
